<template>
    <el-card>
        <el-form :inline="true">
            <el-form-item>
                <el-input placeholder="用户名" v-model="username"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="getList">查询</el-button>
                <el-button @click="clear">清空</el-button>
            </el-form-item>
        </el-form>

        <div style="margin:20px 0">
            <el-button type="primary" @click="add">添加</el-button>
            <el-button type="danger" @click="open" :disabled="!deleteId.length">批量删除</el-button>
        </div>
        <!-- :data="tableState.users" -->
        <!-- @selection-change="handleSelectionChange" -->
        <el-table
        border
        stripe
        :data="list"
        @selection-change="handleSelectionChange"
        >

            <el-table-column
                type="selection"
                width="55"
                prop="daleted" />

            <el-table-column
                type="index"
                label="序号"
                width="80"
                align="center"
            />

            <el-table-column prop="username" label="用户名" width="150" />
            <el-table-column prop="nickName" label="用户昵称" />
            <el-table-column prop="roleName" label="角色列表" width="200"/>
            
            <el-table-column prop="gmtCreate" label="创建时间" width="180"/>
            <el-table-column prop="gmtModified" label="更新时间" width="180"/>

            <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template v-slot="{row}">
                    <el-button 
                    type="info" 
                    size="small" 
                    icon="el-icon-user" 
                    title="分配角色"
                    @click="getRole(row.id, row.username)"
                    />
                    <el-button 
                    type="primary" 
                    size="small" 
                    icon="el-icon-edit-outline" 
                    title="修改用户"
                    @click="show(row)"
                    />
                    <el-popconfirm :title="`确定删除 ${row.username} 吗?`" @onConfirm="deleteUser(row.id)">
                        <template #reference>
                        <span>
                            <el-button 
                            style="margin-left:10px" 
                            type="danger" 
                            size="small" 
                            icon="el-icon-delete" 
                            title="删除用户" 
                            slot="reference" />
                        </span> 
                        </template>
                    </el-popconfirm>
                    </template>
            </el-table-column>
        </el-table>

        <!-- 页码 -->
        <el-pagination
            :current-page.sync="page"
            :page-size.sync="limit"
            :total="total"
            :page-sizes="[3,6,9]"
            style="padding: 20px 0;"
            layout="prev, pager, next, jumper, ->, sizes, total"
            @size-change="getList"
            @current-change="getList"
         />
        <!-- 添加用户dialog -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
        <el-form inline label-width="80px" style="width: 100%;">
          <el-form-item label="用户名">
            <el-input v-model="usermessage.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="usermessage.nickName"></el-input>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="usermessage.password"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
        <!-- 修改dialog -->
        <el-dialog title="修改用户" :visible.sync="dialogVisible2" width="50%">
        <el-form inline label-width="80px" style="width: 100%;">
          <el-form-item label="用户名">
            <el-input v-model="usermessage.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="usermessage.nickName"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="设置角色" :visible.sync="dialogVisible3" width="50%">
        <el-form inline>
          <el-form-item label="用户名">
            <el-input v-model="usermessage.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <template v-slot="{ row }">
              <el-checkbox
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                >全选</el-checkbox
              >
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group
                v-model="assignRoles.idArr"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="role in allRolesList"
                  :label="role.id"
                  :key="role.id"
                  >{{ role.roleName }}</el-checkbox
                >
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateUser">保存</el-button>
          <el-button @click="dialogVisible3 = false">取消</el-button>
        </span>
      </el-dialog>
    </el-card>
</template>
  
<script>
    import { 
        getUserListApi,
        addUserMessageApi,
        deleteUserMessageApi,
        updateUserMessageApi,
        userToAssignApi,
        userDoAssignApi,
        removeUsersApi  
    } from "@/api/acl/user"
    import { Message } from "element-ui"
    import { cloneDeep } from "lodash";
    export default {
      name:'User',
      data() {
        return {
            username: "",
            list: [],
            page: 1,
            limit: 3,
            total: 0,
            deleteArr: [],
            dialogVisible: false,
            dialogVisible2:false,
            dialogVisible3:false,
            usermessage: {
                delete: false,
                nickName: "",
                password: "",
                username: ""
            },
            allRolesList: [],
            assignRoles: {
            roleArr: [],
            idArr: []
            },
            checkAll: false,
            isIndeterminate: true,
            deleteId: []
        }
      },
      methods: {
        // 获取分页列表
        async getList(){
            const result = await getUserListApi(this.page,this.limit,this.username)            
            this.list = result.data.items;
            this.total = result.data.total
        },
        // 清空
        clear(){
            this.username = ''
            this.getList()
        },
        // 添加
        add(){
            this.dialogVisible=true
            this.usermessage={
              delete:false
            }
        },
        async addUser(){
            await addUserMessageApi(this.usermessage)
            this.dialogVisible = false
            Message.success('添加成功')
            this.getList()
            },
        // 删除
        async deleteUser(id){
            await deleteUserMessageApi(id)
            Message.success('删除成功')
            this.getList()
        },
         // 获取角色列表
        async getRole(id, name) {
        this.dialogVisible3 = true;
        this.usermessage.username = name;
        this.usermessage.id = id;
        const result = await userToAssignApi(id);
        this.allRolesList = result.data.allRolesList;
        this.assignRoles.roleArr = result.data.assignRoles.map(
            item => item.roleName
        );
        
        this.assignRoles.idArr = result.data.assignRoles.map(item => item.id);
        },
        handleCheckAllChange(val) {
        const cityOptions = this.allRolesList.map(item => item.id);
        this.assignRoles.idArr = val ? cityOptions : [];
        this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        const cityOptions = this.allRolesList.map(item => item.roleName);
        this.checkAll = checkedCount === cityOptions.length;
        this.isIndeterminate =checkedCount > 0 && checkedCount < cityOptions.length;
        },
         // 分配角色
        async updateUserRole() {
        const roleId = this.assignRoles.idArr.join(",");
        const userId = this.usermessage.id;
        await userDoAssignApi(userId, roleId);
        this.dialogVisible3 = false;
        this.getList();
        },
                // 修改
        /* 显示修改页面，并将数据渲染到dom*/
        show(row){
            this.dialogVisible2=true
            this.usermessage={
                ...row
            }
        },
        async updateUser(role) {
            role = cloneDeep(this.usermessage);
            await updateUserMessageApi(role)
            this.dialogVisible2 = false
            Message.success('修改成功')
            this.getList()
        },
        // 批量删除
        handleSelectionChange(val) {
        console.log(val);
        this.deleteId = val.map(item => item.id);
        console.log(this.deleteId);
        },
        open() {
        this.$confirm("确定要删除吗？", "", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(async () => {
            await removeUsersApi(this.deleteId);
            this.getList();
            this.$message({
                type: "success",
                message: "删除成功!"
            });
            })
            .catch(error => {
            if (error === "cancel") {
                this.$message({
                type: "info",
                message: "已取消删除"
                });
            }
            });
        }
    },
      mounted() {
        this.getList()
      },
    }

</script>
  
<style lang="scss" scoped>
    
</style>